import {extend} from "umi-request";
import {getToken} from "@/plugins/localstorage";
import {message} from "antd";
import {stringify} from "querystring";
import {history} from 'umi';


//
// const authHeaderInterceptor = (url: string, options: RequestConfig) => {
//   const authHeader = { Authorization: `Bearer `+`${getToken()}` };
//   return {
//     url: `${url}`,
//     options: { ...options, interceptors: true, headers: authHeader },
//   };
// };
//
// const demoResponseInterceptors = (response: Response, options: RequestConfig) => {
//   const newHeaders = new Headers(response.headers);
//   newHeaders.append('Authorization', `Bearer`+`${getToken()}`);
//
//   return new Response(response.body, {
//     ...response,
//     headers: newHeaders,
//   });
// };


/**
 * 配置request请求时的默认参数
 */
const request = extend({
  // 新增自动添加AccessToken的请求前拦截器
  // requestInterceptors: [authHeaderInterceptor],
  // responseInterceptors: [demoResponseInterceptors],
  credentials: 'include', // 默认请求是否带上cookie
  prefix: process.env.NODE_ENV === 'production' ? 'www.ait007.cn' : "/api",
  timeout: 1000000
  // requestType: 'form',
});

/**
 * 所有请求拦截器
 */
// request.interceptors.request.use((url, options): any => {
//   console.log(`do request url = ${url}`)
//   return {
//     url,
//     options: {
//       ...options,
//       headers: {
//
//       },
//     },
//   };
// });

// 添加请求拦截器
request.interceptors.request.use((url, options) => {
  const token = getToken(); // 从本地存储中获取 Token
  if (token) {
    const headers = {
      token: `${token}`,
    };
    return {
      url,
      options: { ...options, headers },
    };
  }
  return { url, options };
});

/**
 * 所有响应拦截器
 */

request.interceptors.response.use(async (Response,options): Promise<any> => {
  const res = await Response.clone().json();

  if (res.code === 200){
    return res;
  }

  if(res.code === 401){
    message.error("请先登录");
    localStorage.removeItem('token');
    history.push({
      pathname: '/user/login',
      search: stringify({
        redirect: location.pathname,
      }),
    });
  } else {
    message.error(res.message)
  }
 return res;
});

export default request;
